<template>
  <view class="page-fixed">
    <view class="my-home-page-body">
      <home
        v-if="activeIdx == 0"
        ref="home"
        @scanCode="handleScanCode"
        @inviteCode="handleOpenDlgInviteCode"
        @toWallet="activeIdx = 2"
        @projectsShow="projectsShow"
        @alipayCode="handleOpenDlgAlipayCode"
        @initCompleted="validAcct"
      ></home>
      <market v-if="activeIdx == 1" ref="market"></market>
      <wallet v-if="activeIdx == 2" ref="wallet"></wallet>
      <my v-if="activeIdx == 3" ref="my"></my>
    </view>

    <!-- tabBar -->
    <view class="tab-bar-box">
      <view
        :class="['category-item', index == activeIdx ? 'tab-active' : '']"
        v-for="(item, index) in categories"
        :key="index"
        @click="switchTab(index)"
      >
        <view class="icon">
          <text :class="['iconfont', item.icon]"></text>
        </view>
        <view class="title">{{ item.title }}</view>
      </view>
    </view>

    <!-- 弹窗 - 输入项目邀请码 -->
    <dlg
      ref="dlgInviteCode"
      title="输入项目邀请码"
      @submit="handleSubmitInviteCode"
    >
      <view class="">
        <view class="input-container">
          <text class="input-label">邀请码</text>
          <input
            class="input-field"
            type="text"
            v-model="inviteCode"
            placeholder="请输入项目邀请码"
            placeholder-class="input-placeholder"
            bindinput=""
          />
        </view>
      </view>
      <!-- <template v-slot:footer>
				<view class="dlg-footer-btn">关闭2</view>
				<view class="dlg-footer-btn">确定2</view>
			</template> -->
    </dlg>

    <!-- 弹窗 - 项目列表 -->
    <view
      class="choose-tool-mask"
      v-if="dlgProjectsShow"
      @click="dlgProjectsShow = false"
    >
      <view class="choose-tool-body" @click.stop="() => {}">
        <view class="choose-tool-title">
          {{ `我的项目` }}
        </view>
        <view class=".choose-tool-item-box">
          <view
            class="choose-tool-item"
            v-for="(item, idx) in $refs['home'].projects"
            :key="idx"
            @click="
              $refs['home'].changeCurrentProj(item, idx);
              dlgProjectsShow = false;
            "
          >
            <view class="projects-item">
              <view class="left-part">
                <view class="row1">{{ item.projectName }}</view>
                <view class="row2">{{ item.companyName }}</view>
              </view>
              <span
                :class="
                  'tag-type-' +
                  $utils.getConstantItemByVal(
                    'projectStatus',
                    item.projectStatus
                  ).elType
                "
              >
                {{
                  $utils.getConstantItemByVal(
                    "projectStatus",
                    item.projectStatus
                  ).label
                }}
              </span>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 弹窗 - 我的支付宝 -->
    <dlg
      ref="dlgAlipayCode"
      title="我的支付宝"
      @submit="handleSubmitAlipayCode"
    >
      <view class="">
        <view class="input-container">
          <text class="input-label">支付宝账号</text>
          <input
            class="input-field"
            type="text"
            v-model="alipayCode"
            placeholder="请输入您的支付宝账号"
            placeholder-class="input-placeholder"
            bindinput=""
          />
        </view>
      </view>
    </dlg>

    <!-- 组件 - 《小程序隐私协议》弹窗提示器 -->
    <privacy></privacy>

    <!-- 透明遮罩，未登录时，此遮罩盖住整个页面，点击时跳转登录 -->
    <!-- <view v-if="!token" class="transparent-mask" @click="gotoLogin"></view> -->
  </view>
</template>
<script>
import _ from "lodash";
import commonMixins from "@/mixins/commonMixins";
import home from "@/subPackages/home/home.vue";
import market from "@/subPackages/market/market.vue";
import wallet from "@/subPackages/wallet/wallet.vue";
import my from "@/subPackages/my/index.vue";
import dlg from "@/components/dlg.vue";
import privacy from "@/components/privacy.vue";
export default {
  mixins: [commonMixins],
  components: {
    home,
    market,
    wallet,
    my,
    dlg,
    privacy,
  },
  data() {
    return {
      activeIdx: 0,
      categories: [
        {
          title: "首页",
          icon: "icon-home",
        },
        {
          title: "灵工市场",
          icon: "icon-merchant",
        },
        {
          title: "钱包",
          icon: "icon-wallet",
        },
        {
          title: "我的",
          icon: "icon-mine",
        },
      ],

      currentProjId: "", //当前项目ID
      inviteCode: "", // 项目邀请码
      dlgProjectsShow: false, // 项目列表
      alipayCode: "", // 支付宝账号

      doingScanCode: false, // 正在扫描二维码
    };
  },
  onLoad(e) {
    // 扫码进入本小程序,快速加入项目
    if (e.scene) {
      let scene = decodeURIComponent(e.scene);
      let code_keyword =
        scene && scene.indexOf("=") != -1 && scene.split("=").length >= 2
          ? scene.split("=")[1]
          : "";
      if (code_keyword) {
        // 设置项目邀请状态:待邀请
        uni.setStorageSync("inviteProj", {
          keyword: code_keyword,
          projectId:
            code_keyword.indexOf("_") == -1 ? "" : code_keyword.split("_")[0],
          invited: false, // 待邀请
        });

        // 此时如果未登录则跳转登录
        this.token = uni.getStorageSync("token");
        if (!this.token) {
          this.gotoLogin();
        }
      }
    }
  },
  onShow() {
    this.doInit();
  },
  onPullDownRefresh() {
    this.doInit();
    uni.stopPullDownRefresh();
  },
  methods: {
    // 初始化
    doInit() {
      this.token = uni.getStorageSync("token");
      this.userInfo = uni.getStorageSync("userInfo");
      if (this.token) {
        // 如果未实名
        if (!this.userInfo.name) {
          uni.showToast({
            title: "您尚未实名认证，前往认证中...",
            icon: "none",
            mask: true,
            duration: 10000,
          });
          setTimeout(() => {
            uni.reLaunch({
              url: "/subPackages/my/realname",
            });
          }, 2500);
          return;
        }

        // 如果当前是首页
        if (this.activeIdx == 0) {
          if (!this.doingScanCode) {
            this.$refs["home"].handleInit(
              this.$refs["home"].currentProj.id,
              () => {
                // 如果是扫码进入小程序
                let inviteProj = uni.getStorageSync("inviteProj");
                if (inviteProj) {
                  // 还没有加入项目
                  if (!inviteProj.invited) {
                    // 加入项目
                    this.joinProj(1, inviteProj.keyword);
                    return;
                  }
                } else {
                  // 未登录的情况下，用户在灵工市场点击申请了某个项目后，系统会引导用户前往登录，登录完成后回到首页，继续自动申请加入项目
                  let applyJob = uni.getStorageSync("applyJob");
                  if (applyJob) {
                    uni.removeStorageSync("applyJob");
                    // 自动申请加入项目
                    this.handleApply(applyJob);
                    return;
                  }
                }
              }
            );
          }
        } else if (this.activeIdx == 1) {
          this.$refs["market"].handleInit();
        } else if (this.activeIdx == 2) {
          this.$refs["wallet"].handleInit();
        } else if (this.activeIdx == 3) {
          this.$refs["my"].handleInit();
        }
      }
    },
    // 去登录
    gotoLogin() {
      uni.showToast({
        title: "您尚未登录，跳转登录中...",
        icon: "none",
        mask: true,
      });
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/login",
        });
      }, 1500);
    },
    // 切换标签页
    switchTab(index) {
      if (this.$refs["home"] && this.$refs["home"].currentProj.id) {
        this.currentProjId = this.$refs["home"].currentProj.id;
      }
      this.activeIdx = index;
    },
    // 加入项目
    // type: 1二维码 2邀请码
    // keyword: 项目id_类型(1员工邀请 2渠道邀请 3渠道邀请员工)
    // callback: 回调
    joinProj(type = 1, keyword = "", callback = () => {}) {
      this.$request.invite(
        {
          jump_url: "", // "/pages/index",
          type: type, // 1二维码 2邀请码
          keyword: keyword,
        },
        (res) => {
          // 设置项目邀请状态:已邀请
          uni.setStorageSync("inviteProj", {
            keyword: keyword,
            projectId: keyword.indexOf("_") == -1 ? "" : keyword.split("_")[0],
            invited: true, // 已邀请
          });
          // 去签约
          if (res.status == 1) {
            uni.showToast({
              title: "前往签约中..",
              icon: "none",
              mask: true,
              duration: 2000,
            });
            setTimeout(() => {
              this.toPath(
                `/subPackages/signing/thirdPartyUrl?url=${encodeURIComponent(
                  this.$utils.fmtFDDUrl(res.url)
                )}`
              );
            }, 1500);
            this.$refs["home"].currentProj.id = null; // 把ID清掉，签约返回后，会自动选中最新的一个项目作为当前项目
          }
          // 不用签约，直接加入成功
          else {
            uni.showToast({
              title: "申请成功,请等待审核",
              icon: "none",
              mask: true,
              duration: 2000,
            });
            setTimeout(() => {
              this.$refs["home"].handleInit();
            }, 1500);
          }
        },
        (err) => {
          // 如果报错，基本上一定是报"已经加入过项目"的错
          // 设置项目邀请状态:已邀请
          uni.setStorageSync("inviteProj", {
            keyword: keyword,
            projectId: keyword.indexOf("_") == -1 ? "" : keyword.split("_")[0],
            invited: true, // 已邀请
          });
          callback();
        },
        () => {
          callback();
        }
      );
    },

    // 当前项目开户
    validAcct(proj) {
      let inviteProj = uni.getStorageSync("inviteProj");
      if (
        proj.can_use_bank &&
        !proj.bank_name &&
        inviteProj &&
        (inviteProj.projectId == proj.id || !inviteProj.projectId) &&
        inviteProj.invited &&
        !inviteProj.reminderd
      ) {
        // 兴业银行没有开户操作，注释掉
        // uni.showModal({
        //   title: "温馨提示",
        //   content: "开户后才能提现到银行卡，是否立即开户？",
        //   confirmText: "确定",
        //   cancelText: "暂不开户",
        //   success: (res) => {
        //     if (res.confirm) {
        //       // 去开户(估计是跳第三方) xxx
        //       // this.toPath(`/subPackages/signing/thirdPartyUrl?url=${encodeURIComponent('https://www.iconfont.cn/?spm=a313x.home_index.i3.2.5b8e3a81XlWBmS')}`);
        //     }
        //   },
        // });
        inviteProj.reminderd = true; // 已提醒开户(只提醒一次)
        uni.setStorageSync("inviteProj", inviteProj);
      }
    },

    // 扫码 - 加入项目
    handleScanCode() {
      this.doingScanCode = true;
      uni.scanCode({
        scanType: ["wxCode"],
        success: (res) => {
          if (
            res.path &&
            res.path.indexOf("scene=") != -1 &&
            res.path.split("scene=").length >= 2
          ) {
            // const decodedData = atob(res.rawData); // Base64 解码
            // console.log('解码结果:', decodedData);
            const queryStr = decodeURIComponent(res.path.split("scene=")[1]);
            const obj = _.chain(queryStr)
              .split("&")
              .map((param) => {
                const [key, val] = param.split("=");
                return [
                  decodeURIComponent(key),
                  val ? decodeURIComponent(val) : null, // 处理空值
                ];
              })
              .fromPairs()
              .value();
            // 加入项目
            this.joinProj(1, obj.keyword);
          } else {
            uni.showToast({
              title: "无效的二维码",
              icon: "none",
              duration: 1500,
              mask: true,
            });
          }
        },
        fail: (res) => {},
        complete: () => {
          this.doingScanCode = false;
        },
      });
    },

    // 弹窗 - 输入项目邀请码
    handleOpenDlgInviteCode() {
      this.inviteCode = "";
      this.$refs["dlgInviteCode"].show();
    },
    // 弹窗 - 输入项目邀请码 - 提交
    handleSubmitInviteCode() {
      // 表单验证
      if (!this.inviteCode) {
        uni.showToast({
          title: "请输入邀请码",
          icon: "none",
          duration: 1500,
          mask: true,
        });
        return;
      }
      // 加入项目
      this.joinProj(2, this.inviteCode, () => {
        this.$refs["dlgInviteCode"].hide();
      });
    },

    // 弹窗 - 项目列表
    projectsShow() {
      this.dlgProjectsShow = true;
    },
    // 弹窗 - 输入支付宝账号
    handleOpenDlgAlipayCode() {
      this.alipayCode = this.$refs["home"].currentProj.alipay_account;
      this.$refs["dlgAlipayCode"].show();
    },
    // 保存支付宝账号
    handleSubmitAlipayCode() {
      if (!this.alipayCode) {
        uni.showToast({
          title: "请输入支付宝账号",
          icon: "none",
          duration: 1500,
          mask: true,
        });
        return;
      }

      // 调用接口保存支付宝账号
      let account_id = this.$refs["home"].currentProj.account_id;
      let apiName = "";
      let params = {};
      if (!account_id) {
        params.institution_id = this.$refs["home"].currentProj.institution_id;
        params.bank_card = this.alipayCode;
        apiName = "userOpenAccount";
      } else {
        params.account_id = account_id;
        params.bank_card = this.alipayCode;
        apiName = "userEditAccount";
      }
      return this.$request[apiName](params, (res) => {
        this.$refs["dlgAlipayCode"].hide();
        uni.showToast({
          title: "支付宝账号设置成功",
          icon: "none",
          mask: true,
          duration: 1500,
        });
        setTimeout(() => {
          this.$refs["home"].handleInit(this.$refs["home"].currentProj.id);
        }, 1500);
      });
    },

    // 自动申请加入项目
    handleApply(proj) {
      this.$request.inviteProject(
        {
          type: 4, // 写死
          keyword: `${proj.project_id}_4`, // 写死
          jump_url: "",
          isLoading: true,
          loadingMsg: `正在申请项目..`,
        },
        (res) => {
          if (res.url) {
            // 跳转签约
            uni.showToast({
              title: "前往签约中..",
              icon: "none",
              mask: true,
              duration: 2000,
            });
            setTimeout(() => {
              this.toPath(
                `/subPackages/signing/thirdPartyUrl?url=${encodeURIComponent(
                  this.$utils.fmtFDDUrl(res.url)
                )}`
              );
            }, 1500);
          } else {
            // 无需签约
            uni.showToast({
              title: "项目申请成功！",
              icon: "none",
              mask: true,
              duration: 2000,
            });
            setTimeout(() => {
              this.$refs["home"].handleInit();
            }, 1500);
          }
        }
      );
    },
  },
  watch: {
    activeIdx(nvl, ovl) {
      this.$nextTick(() => {
        if (nvl == 0) {
          this.$refs["home"].handleInit(this.currentProjId);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
// 引入sass样式变量(本来想全局引入，但是不成功，以后有空再解决)
@import "@/static/scss/variables.scss";

.page-fixed {
  .my-home-page-body {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: $tabBarH;
    bottom: calc(#{$tabBarH} + constant(safe-area-inset-bottom));
    bottom: calc(#{$tabBarH} + env(safe-area-inset-bottom));
    background-color: $colorSubBg;
    overflow-y: auto;
  }

  .tab-bar-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    bottom: calc(0px + constant(safe-area-inset-bottom));
    bottom: calc(0px + env(safe-area-inset-bottom));
    height: $tabBarH;
    background-color: white;
    display: flex;
    justify-content: space-around;
    align-items: center;
    z-index: 10;
    box-shadow: 0px -2px 4px rgba(0, 0, 0, 0.1);
    color: $colorMinorFont;

    .category-item {
      width: 30vw;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .icon {
        .iconfont {
          font-size: 6vw !important;
        }

        margin: 1.5vw 0 0.8vw 0;
      }

      .title {
        font-size: 3vw;
        margin: 0 0 1.5vw 0;
      }
    }
  }

  .tab-active {
    color: $colorPrimary;
  }
}

.projects-item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left-part {
    display: flex;
    flex-direction: column;

    .row1 {
    }

    .row2 {
      font-size: $minFontSize;
      color: $colorMinorFont;
      margin-top: 2vw;
    }
  }
}

.transparent-mask {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9999999;
}
</style>
<style lang="scss"></style>
